package common.web.action;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import common.log.util.LogModule;
import common.log.util.LogType;
import common.log.vo.WebLog;
import common.rbac.po.Authority;
import common.rbac.po.GroupRole;
import common.rbac.po.Role;
import common.rbac.po.RoleAuthority;
import common.util.JSONUtils;
import common.web.vo.Result;

@Controller
@RequestMapping("/system/role")
public class RoleAction  extends CommonAction  {

	@RequestMapping("/view/{id}")
	@ResponseBody
	public Result view(@PathVariable String id) {
		Role role = this.baseService.get(Role.class, id);
		if (null == role) {
			return Result.fail("组不存在");
		}
		Result result = Result.createResult(role);

		// 查询关联的权限
		RoleAuthority ra = new RoleAuthority();
		ra.setRoleId(role.getId());
		result.addMap("auths", this.baseService.findByExample(ra));
		return result;
	}
	
	@RequestMapping("/viewAuth/{id}")
	@ResponseBody
	public Result viewAuth(@PathVariable String id) {
		return Result.createResult(this.baseService.find("select sp from RoleAuthority rp,Authority sp where rp.authId = sp.id and rp.roleId = ?", id));
	}
	
	@RequestMapping("/editAuth/{id}")
	@ResponseBody
	public Result editAuth(@PathVariable String id) {
		// 查询关联的权限
		RoleAuthority ra = new RoleAuthority();
		ra.setRoleId(id);
		Authority auths = new Authority();
		Result result = Result.createResult(this.baseService.findByExample(auths));
		result.addMap("list", this.baseService.findByExample(ra));
		return result;
	}

	@RequestMapping("/list")
	@ResponseBody
	public Result list(@RequestBody JSONObject json) {
		return super.list(json, Role.class);
	}
	@RequestMapping("/listAll")
	@ResponseBody
	public Result listAll() {
		return Result.createResult(this.baseService.loadAll(Role.class));
	}
		
	@RequestMapping("/saveAuth/{roleId}")
	@ResponseBody
	public Result saveAuth(@PathVariable String roleId, @RequestBody JSONObject json) {
		JSONObject map = json.getJSONObject("selectAuths");
		Set<String> keySet = map.keySet();
		String hql = "delete from RoleAuthority where roleId = ? ";
		//json.getst
		List<RoleAuthority> list = new ArrayList<>();
		for (String pid : keySet) {
			RoleAuthority sp = new RoleAuthority();
			sp.setRoleId(roleId);
			sp.setAuthId(pid);
			list.add(sp);
		}
		baseService.dbOperation(hql, new Object[]{roleId}, list.toArray(), null, null);
		return Result.SUCCESS;
	}

	@RequestMapping("/{editType}")
	@ResponseBody
	public Result save(@PathVariable String editType, @RequestBody JSONObject json) {
		Role role = JSONUtils.toJavaObject(json.getJSONObject("entity"), Role.class);
		if (null != role) {
			WebLog log = new WebLog(LogModule.ROLE, LogType.ADD, "操作失败");
			if ("update".equals(editType)) {
				log.setType(LogType.UPDATE);
			}
			try {
				// 删除关联部分
				if ("update".equals(editType)) {
					super.setCommonUpdateInfo(role);
					baseService.update(role);
					log.setSuccess(MessageFormat.format("修改角色[{0}]成功!", role.getName()));
				} else if ("add".equals(editType)) {
					super.setCommonSaveInfo(role);
					baseService.save(role);
					log.setSuccess(MessageFormat.format("新增角色[{0}]成功!", role.getName()));
				}
			} catch (Exception e) {
				log.setFail(MessageFormat.format("操作角色[{0}]失败!", role.getName()));
				logger.error("", e);

				return Result.fail("数据错误，请刷新后重试");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("数据错误，请刷新后重试");
		}
		return Result.SUCCESS;
	}

	@RequestMapping("/delete/{id}")
	@ResponseBody
	public Result delete(@PathVariable String id) {
		Role load = baseService.get(Role.class, id);
		if (null != load) {

			WebLog log = new WebLog(LogModule.ROLE, LogType.DELETE, "操作失败");
			try {
				List<Object> deletes = new ArrayList<>();

				// 关联的查询出来一起删除
				RoleAuthority ra = new RoleAuthority();
				ra.setRoleId(load.getId());
				GroupRole gr = new GroupRole();
				gr.setRoleId(load.getId());

				// 删除关联部分
				deletes.addAll(baseService.findByExample(ra));
				deletes.addAll(baseService.findByExample(gr));
				deletes.add(load);

				baseService.delete(deletes.toArray());

				log.setSuccess(MessageFormat.format("删除角色[{0}]成功!", load.getName()));
			} catch (Exception e) {
				log.setFail(MessageFormat.format("删除角色[{0}]失败!", load.getName()));
				logger.error("", e);

				return Result.fail("删除失败");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("角色不存在");
		}
		return Result.SUCCESS;
	}
	
}
